<template>
  <q-menu anchor="bottom right" self="top right" :offset="[0, 10]" class="comp-UserProfileMenu">
    <header class="q-pa-md">
      <div class="ellipsis text-weight-bold" style="font-size: 15px;">{{ viewer.staff.name || `ID: ${viewer.staff.id}` }}</div>
      <div class="ellipsis text-grey-7" style="margin-top: 7px;">{{ mask(viewer.staff.phoneNumber || viewer.staff.email) }}</div>
    </header>
    <q-separator inset />
    <q-list dense padding>
      <q-item clickable v-close-popup class="menu-item" to="/usercenter/profile">
        <q-item-section side>
          <q-icon name="account_circle" color="text" />
        </q-item-section>
        <q-item-section>个人资料</q-item-section>
      </q-item>
      <q-item clickable v-close-popup class="menu-item" to="/usercenter/settings">
        <q-item-section side>
          <q-icon name="security" color="text" />
        </q-item-section>
        <q-item-section>帐号与安全</q-item-section>
      </q-item>
    </q-list>
    <q-separator inset />
    <q-list dense padding>
      <q-item clickable v-close-popup class="menu-item" @click="handleLogout">
        <q-item-section>退出登录</q-item-section>
      </q-item>
    </q-list>
  </q-menu>
</template>

<script>
import { defineComponent } from 'vue'
import { storeToRefs } from "pinia"
import { useQuasar } from 'quasar'
import { authApi } from 'src/api/auth'

import { useStore } from 'stores/default'
import { mask } from 'src/utils/string'

export default defineComponent({
  name: 'UserProfileMenu',
  setup() {
    const store = useStore()

    const $q = useQuasar()
    const { viewer } = storeToRefs(store)

    const handleLogout = async () => {
      try {
        // 先执行后端退出
        const response = await authApi.logout()

        if (response.data.code == 200) {
          // 后端退出成功后，再执行前端清理
          localStorage.removeItem('token')
          store.setUserInfo(null)

          $q.notify({
            type: 'positive',
            message: '退出成功'
          })

          window.location.href = response.data.data.sso_logout_url
          return
        }else{
          $q.notify({
            type: 'negative',
            message: response.data.message || '退出失败'
          })
        }
      } catch (error) {
        $q.notify({
          type: 'negative',
          message: error.message || '退出失败'
        })
      }
    }

    return {
      viewer,
      mask,
      handleLogout
    }
  }
})
</script>

<style lang="scss">
.comp-UserProfileMenu {
  width: 200px;
  padding-top: 4px;
  padding-bottom: 4px;

  header {
    line-height: 1;
  }

  .menu-item {
    cursor: pointer;

    .q-icon {
      font-size: 20px;
      color: $grey;
    }

    &:hover {
      color: $primary;
    }

    .q-item__section--side {
      padding-right: 6px;
    }
  }

  .q-separator {
    background: $grey-3;
  }
}
</style>
